$(document).ready(function(){
    /**
     * js Date类型格式化
     * @param 格式 如"yyyy-MM-dd hh:mm:ss"
     * 
     * @return 时间字符串
     */
    Date.prototype.format = function(format){ 
        var o = { 
            "M+" : this.getMonth()+1, //month 
            "d+" : this.getDate(), //day 
            "h+" : this.getHours(), //hour 
            "m+" : this.getMinutes(), //minute 
            "s+" : this.getSeconds(), //second 
            "q+" : Math.floor((this.getMonth()+3)/3), //quarter 
            "S" : this.getMilliseconds() //millisecond 
            } 

        if(/(y+)/.test(format)) { 
            format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
        } 

        for(var k in o) { 
            if(new RegExp("("+ k +")").test(format)) { 
                format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); 
            } 
        } 
        return format; 
    } 
    
    //默认配置
	var defaults = {
		defaultClass : 'menu_tree', //树状导航 默认class
		padding_left: 15, //每一级左侧距离
		requestUrl:'',
		requestData:'',
	};
    var opts = {};
    /**
	 * 生成树状菜单
	 * @param data
	 * @returns
	 */
	function createMenuTree(data,index){
		var ul = $("<ul class='"+opts.defaultClass+"'></ul>");
		var padding = opts.padding_left*(index+1);
		$.each(data,function(i,item){
			var li = $("<li></li>");
			var a = $("<a href='javascript:;' data-areaId='"+item.areaId+"'>"+item.areaName+"</a>");
			var span = $("<span style='padding-left:"+padding+"px'></span>");
			var children = "";
			if(item.childrens.length>0){
				a.addClass("parent");
				children = createMenuTree(item.childrens,index+1);
			}
			
			span.append(a);
			li.append(span);
			if(children!=""){
				children.hide();
				li.append(children);
			}
			
			ul.append(li);
		});
		return ul;
	}
	
    
    $.fn.extend({  
		"menuTree":function(options,callback){
			var target = this;
			opts = $.extend(defaults, options); //合并配置数据
			
			$.ajax({
				type : 'POST',
				url:opts.requestUrl,
				contentType : 'application/json',
				data: opts.requestData,
				dataType : 'json',
				success:function(data){
					var area = data.area;
					var a = target.find(".header-title").children("a");
					a.text(area.areaName+a.text());
					a.attr('data-areaid',area.areaId);
					a.on("click",function(){
						var tree = target.find(".operation-body").children(".menu_tree");
						tree.find(".menu_tree").hide();
					});
					//a.attr("onclick","queryByArea(event,this,"+area.areaId+");");
					target.children(".operation-body").append(createMenuTree(area.childrens,1));
					//li绑定点击切换事件
					target.find("li").on("click",function(event){
				    	event.stopPropagation();    //标准   
				    	event.cancelBubble = true;  //IE
				    	var lis = $(this).siblings("li");
				    	if(lis.find("ul").is(":visible")){
				    		lis.find("ul").slideUp();
				    	}
				    	
				    	var target = $(this).children("a");
				    	if(target.hasClass("active")){
				    		target.removeClass("active");
				    	}else
				    		target.addClass("active");
				    	$(this).children("ul").slideToggle();
				    });
					target.find("a").on("click",function(event){
						 $("."+opts.defaultClass).find("span.selected").removeClass("selected");
					     $(this).parent().addClass("selected");
					     if(callback!=undefined&&typeof(eval(callback))=="function"){
					    	 var id = $(this).attr('data-areaid');
					    	 callback(event,this,id);
					     }
					});
					
					target.children(".operation-body").slideToggle();
				},
				error:function(){
					//alert("Post请求失败！");
				}
			});
		},
		"dropDownMenu":function(){
			this.each(function(i,item){
				$(item).css("bottom","-"+ ($(item).height() + 1) +"px");
				var parent = $(item).parent();
				parent.hover(function(){
			        $(this).children("ul").show();
			    },function(){
			        $(this).children("ul").hide();
			    });
				
			});
		},
		"dropSideMenu":function(){
			this.each(function(i,item){
				$(item).css("top","-31px");
				var parent = $(item).parent();
				parent.hover(function(){
			        $(this).children("ul").show();
			    },function(){
			        $(this).children("ul").hide();
			    });
				
			});
		}
	});  
    
    /**
     * 工作台 时间 计算
     * 
     */
    function setTime(){
    	 var time = (new Date()).format("yyyy-MM-dd hh:mm");
         $("#clock").text(time);
    }
    setTime();
    setInterval(function () {
    	setTime();
    },1000);
    
    /**
     *初始化导航栏的下拉菜单
     */
  

    
    /**
     * 返回顶部 初始化
     */
    var bt = $('#toolBackTop');
	var sw = $(document.body)[0].clientWidth;

	var limitsw = (sw - 1200) / 2 - 100;
	
	if (limitsw > 0){
       	limitsw = parseInt(limitsw);
        bt.css("right",limitsw);
	}

	$(window).scroll(function() {
        var st = $(window).scrollTop();
        if(st > 30){
                bt.show();
        }else{
                bt.hide();
        }
	});

	bt.click(function(){
		$("html,body").animate({scrollTop:0},500);
	});

    /**
     * 侧边栏树状导航切换
     * @param  JQuery Object  target  需要切换对象
     * @param  Boolean show   是否变为显示
     * 
     */
    function sidebarToggle(target,show){
        if(show){
             target.addClass("active");
        }else{
            target.removeClass("active");
        }
        target.children(".sidebar-content").slideToggle();
    }

    /**
     * 侧边栏树状导航点击切换
     */
    $("#areaBlock").on("click",".sidebar-title",function(){
        var target = $(this).parent(".sidebar-item");

        if(target!=undefined&&target.hasClass("active")){
            sidebarToggle(target,false);
        }else{
            sidebarToggle($(".sidebar-item.active"),false);
            sidebarToggle(target,true);
        } 
    });
    
   /* $("#areaBlock").on("click",".sidebar-nav li",function(){
    	if(!$(this).hasClass("active")){
    		$(".sidebar-nav").find("li.active").removeClass("active");
        	$(this).addClass("active");
    	}
    	
    });*/

    /**
     * 侧边栏点击切换操作
     */
    /*$("#sidebar .header").click(function(){
        var target = $("#sidebar .operation-body");
        if(!target.is(":animated")){ 
            target.slideToggle();
        }
    });*/
    /*$("#sidebar .header .header-title a").click(function(){
        var body = $("#areaBlock .operation-body");
    	body.find(".active").removeClass("active");
    	body.find(".sidebar-content").slideUp();
    });
    */
    

    /**
     * 初始化所有pop弹窗
     * @param  Integer index 数组索引
     * @param  DOM Object item  数组中当前迭代元素对象
     * 
     */
    $.each($(".pop-btn"),function(index,item){
    	initPop(index,item);
    });
    
    /**
     *登陆用户名称的下拉菜单功能
     * 
     */
    var mouseInSetting = false;
    $("#username").mouseenter(function(){
        $(this).siblings(".dropdown-content").slideDown("fast");
    });

    $("#username").mouseleave(function(){
        setTimeout(function(){
            if(mouseInSetting==false)
                $("#setting").slideUp("fast");
        },300);
    });

    $("#setting").mouseenter(function(){
        mouseInSetting = true;
    });

    $("#setting").mouseleave(function(){
        mouseInSetting = false;
        $(this).slideUp("fast");
    });

        
});
	
	function getPageNation(target,total,pagesize,current,onclick){
		var pageNum = 0;
		if(total==undefined)
			total=0;
		
		if(pagesize>0)
			pageNum = parseInt(total/pagesize);
		if(total%pagesize>0)
			pageNum++;
		
		 var ul = $("<ul class='pagination pagination-default'></ul>");
		 ul.append($("<span>总共&nbsp;<strong id='recordNum'>"+total+"</strong>&nbsp;条记录</span>"));
		 if(current>1){
			 ul.append($("<li class='pagination-first'>"+
					 		"<a href='javacript:;' onclick='"+onclick+"(1);'>第一页</a>"+
			 			 "</li>"));
			 ul.append($("<li class='pagination-prev'>"+
				 		"<a href='javacript:;' onclick='"+onclick+"("+(parseInt(current)-1)+");'>上一页</a>"+
		 			 "</li>"));
		 }
		 var count = 1;
		 if(current>10)
			 count= current - 5;
		 if(pageNum>10&&pageNum<(current+10))
			 count = pageNum - 9;
		 for(var i = count;i<=pageNum&&i<count+10&&pageNum>1;i++){
			 if(i==current)
				 ul.append($("<li class='active'><a href='javascript:;'>"+i+"</a></li>"));
			 else
				ul.append($("<li><a href='javascript:;' onclick='"+onclick+"("+i+")'>"+i+"</a></li>"));
		}
        if(i<pageNum&&pageNum>10)
        	ul.append($("<li><a href='javascript:;' onclick='"+onclick+"("+i+")'>…</a></li>"));
		
         if(current<pageNum){
        	 ul.append($("<li class='pagination-next'>"+
				 		"<a href='javacript:;' onclick='"+onclick+"("+(parseInt(current)+1)+");'>下一页</a>"+
		 			 "</li>"));
        	 ul.append($("<li class='pagination-last'>"+
			 		"<a href='javacript:;' onclick='"+onclick+"("+pageNum+");'>最末页</a>"+
	 			 "</li>"));
         }
         target.empty();
         target.append(ul);
	}
    
    
    function initPop(index,item){
        var position = $(item).attr("pop-position");
        var type = $(item).attr("pop-trigger");
        var pop = $("<div class='popover'>"+
                    "<div class='popover-caret' ></div>"+
                "</div>");
        var content = $("<div class='popover-inner'>"+$(item).attr("pop-data")+"</div>");
        var caret = pop.children(".popover-caret");
        
        if(position=="right"){
        	pop.addClass("popover-right")
        }else if(position=="top")
            pop.addClass("popover-top");
        
        pop.prepend(content);
        pop.insertAfter($(item));
        
        var p = $(item).position();
        var popLeft = p.left - ((pop.width()-12)-$(item).width())/2;
        var popTop = 0;
        
        if(position=="bottom"){
            popTop = p.top + $(item).innerHeight() + 5;
            caret.css("top","-6px");
            caret.css("left",(pop.width()-12)/2+"px");
        }else if(position=="right"){
        	popTop = p.top-(pop.innerHeight()-$(item).height())/2;
        	popLeft = p.left+$(item).innerWidth();
        	caret.css("top",(pop.innerHeight()-$(item).innerHeight()+6)/2+"px");
        	caret.css("left","-6px");
        }else{
        	popTop = p.top - pop.height()-10;
        	caret.css("left",(pop.width()-12)/2+"px");
        }
            
        pop.css({"left":popLeft+"px","top":popTop+"px"});
        	
        if(type=="hover"){
            $(item).on("mouseover",function(){
                var popover = $(this).next(".popover");
                popover.addClass("active");
            });
            $(item).on("mouseout",function(){
                var popover = $(this).next(".popover");
                popover.removeClass("active");
            });
        }else if(type="click"){
        	$(item).off("click");
            $(item).on("click",function(){
                 var popover = $(this).next(".popover");
                 if(popover.hasClass("active"))
                    popover.removeClass("active");
                else
                    popover.addClass("active");
            });
        }
    }
    
    /*** 公用的异步请求函数  **/
    //默认ajax参数
    var ajaxOpts = {
		timeout : 60000, //超时时间设置，单位毫秒
		timeoutcallback : function(){alert("连接超时,请重新操作。");},
    };
    /**
	 * ajax post 请求
	 * @param url 请求路径
	 * @param requsetData 请求数据
	 * @param callback 回调操作
	 */
	function post(url,requsetData,callback,options){
		var opts;
		if(typeof(options) != "undefined"){
			opts = $.extend(opts,options); //合并配置数据
		}else{
			opts = ajaxOpts;
		}
		$.ajax({
			type : 'POST',
			url:url,
			contentType : 'application/json',
			data: requsetData,
			dataType : 'json',
			timeout : opts.timeout,
			success:function(data){
				if(data.resultcode=="-1"){
					alertDialog("当前登陆状态已过期，请重新登陆！",function(){
						window.location.reload();
					});
					return;
				}
				if(callback!=undefined&&typeof(eval(callback))=="function")
					callback(data);
			},
			error:function(XMLHttpRequest,textStatus,errorThrown){
				if(textStatus == "timeout"){
					if(opts.timeoutcallback!=undefined&&typeof(eval(opts.timeoutcallback))=="function")
						opts.timeoutcallback();
				}
				if(opts.errorcallback!=undefined&&typeof(eval(opts.errorcallback))=="function")
					opts.errorcallback();
			}
		});
	}
	
	/**
	 * ajax get 请求
	 * @param url 请求路径
	 * @param callback 回调函数
	 */
	function get(url,callback){
		$.ajax({
			type : 'GET',
			url:url,
			dataType : 'text',
			success:function(data){
				if(callback!=undefined&&typeof(eval(callback))=="function")
					callback(data);
			},
			error:function(){
				//alert("Get请求失败！");
			}
		});
	}
    
	/**
	 * 提示框
	 * @param msg
	 * @param callback
	 */
	function confirmDialog(msg,callback){
		$.dialog({
			lock:true,
    		opacity:.5,
			title:"确认提示",
			effect:'i-super-scale',
  			width:300,
  			content:msg,
  			btn: {                      //可以任意定义按钮个数
    			ok: {                     //按钮的key值，下次可用个btn方法从新设置
      				val: '确定',            //按钮显示的文本
      				type: 'green',         //样式可选参数green, blue, red, yellow .默认白色。
	      			click: function(btn) {
	      				callback();
      				}
    			},
    			cancle: {                //第四个按钮
      				val: '取消'
    			}
  			}
		});
	}
	
	/**
	 * 警告框
	 * @param msg
	 * @param callback
	 */
	function alertDialog(msg,callback){
		$.dialog({
			lock:true,
    		opacity:.5,
			title:"提示信息",
			effect:'i-super-scale',
  			width:300,
  			content:msg,
  			btn: {                      //可以任意定义按钮个数
    			ok: {                     //按钮的key值，下次可用个btn方法从新设置
      				val: '确定',            //按钮显示的文本
      				type: 'green',         //样式可选参数green, blue, red, yellow .默认白色。
	      			click: function(btn) {
	      				callback();
      				}
    			}
  			}
		});
	}
    
    /**
     * 修改密码相关js脚本
     */

    function comfirmChangePsd(which){
    	$(which).attr("disabled","disabled");
    	$(which).text("请求处理中…");
    	$("#changePsdResult").hide();
    	var text = checkData();
    	if(text == ""){
    		$(which).text("确认保存");
    		$(which).removeAttr("disabled");
    		return;
    	}
    		
    	var newpassword = $("#newPassword").val();
    	var url=ctx+"/account/changePsd/"+newpassword;
    	
    	$.ajax({
    		type : 'POST',
    		url:url,
    		contentType : 'application/json',
    		data: text,
    		dataType : 'text',
    		success:function(data){
    			$(which).removeAttr("disabled");
    			$(which).text("确认保存");
    			if(data=="success"){
    				$("#changePsdForm").find("input[type='password']").val("");
    				$(".prompt").removeClass("error");
    				$(".prompt").removeClass("icon-ok");
    				$(".prompt").text("");
    				setOperationSuccess();
    			}else{
    				$("#changePsdResult").removeClass("alert-success");
    				$("#changePsdResult").addClass("alert-danger");
    				$("#changePsdResult").text("修改密码失败！");
    				$("#changePsdResult").show();
    			}					
    		},
    		error:function(){
    			$(which).removeAttr("disabled");
    			$(which).text("确认保存");
    			alert("请求异常！");
    		}
    	});
    }

    function setOperationSuccess(){
    	$("#changePsdResult").removeClass("alert-danger");
    	$("#changePsdResult").addClass("alert-success");
		$("#changePsdResult").text("修改密码成功！");
		$("#changePsdResult").show();
		setTimeout("$('#changePsdBlock').modal('hide');",1500);
    }

    function checkData(){
    	var result = true;
    	var accountId = $("#changePsdForm").find("input[name='accountId']").val();
    	var password = $("#oldPassword").val();
    	var newpassword = $("#newPassword").val();
    	var repassword = $("#rePassword").val();

    	$(".prompt").text("");
    	if(StringIsNullorEmpty(accountId) || accountId <= 0){
    		result = false;
    	}
    	
    	var span = $("#oldPassword").siblings(".prompt");
    	if(span.hasClass("error")){
    		setError(span,"原密码不正确！");
    		result = false;
    	}

    	if(StringIsNullorEmpty(password)){
    		setError(span,"原密码不可为空！");
    		result = false;
    	}
    	
    	if(!checkNewPassword())
    		result = false;
    	
    	if(!checkRePassword())
    		result = false;
    	
    	if(result)
    		return JSON.stringify({accountId:accountId,password:password});
    	else
    		return "";
    }

    //异步检查当前输入原密码是否正确
    function checkOldPassword(callback){
    	var accountId = $("#changePsdForm").find("input[name='accountId']").val();
    	var password = $("#oldPassword").val();
    	var text = JSON.stringify({accountId:accountId,password:password});
    	var url=ctx+"/account/checkPassword";
    	
    	$.ajax({
    		type : 'POST',
    		url:url,
    		contentType : 'application/json',
    		data: text,
    		dataType : 'text',
    		success:function(data){
    			
    			if(callback!=undefined&&typeof(eval(callback))=="function")
    				callback(data);
    						
    		},
    		error:function(){
    			alert("请求异常！");
    		}
    	});
    }

    function setOK(target){
    	target.removeClass("error");
    	target.addClass("icon-ok");
    	target.text("");
    }

    function setError(target,msg){
    	target.removeClass("icon-ok");
    	target.addClass("error");
    	target.text(msg);
    }

    function checkNewPassword(){
    	var newpassword = $("#newPassword").val();
    	var span = $("#newPassword").siblings(".prompt");
    	if(StringIsNullorEmpty(newpassword)){
    		setError(span,"新密码不可为空！");
    		return false;
    	}else{
    		setOK(span);
    	}
    	return true;
    }

    function checkRePassword(){
    	var newpassword = $("#newPassword").val();
    	var repassword = $("#rePassword").val();
    	var span = $("#rePassword").siblings(".prompt");
    	if(repassword!=newpassword){
    		if(StringIsNullorEmpty(repassword))
    			setError(span,"请输入重复密码！");
    		else
    			setError(span,"密码不一致！");
    		return false;
    	}else{
    		if(!StringIsNullorEmpty(newpassword)){
    			setOK(span);
    			return true;
    		}	
    	}
    	return false;
    }


    function StringIsNullorEmpty(string){
    	
    	if(string==undefined || string =="")
    		return true;
    	else
    		return false;
    }

    $(document).ready(function(){
    	$('#changePsdBlock').on('show.bs.modal', function (e) {
    		$("#changePsdResult").hide();
    	});
    	$("#oldPassword").blur(function(){
    		if($("#oldPassword").val()!="")
    			checkOldPassword(function(data){
    				var span = $("#oldPassword").siblings(".prompt");
        			
        			if(data=="success"){
        				setOK(span);
        			}else{
        				setError(span,"原密码不正确！");
        			}	
    			});
    	});
    	
    	$("#newPassword").blur(function(){
    		checkNewPassword();
    	});
    	
    	$("#rePassword").blur(function(){
    		checkRePassword();
    	});
    	
    	/**
    	 * 初始化时间选择器
    	 */
    	$(".query-date-picker").each(function(i,item){
    		new Pikaday(
        	{
            	field: item,
            	firstDay: 1,
            	minDate: new Date('2000-01-01'),
           	 	maxDate: new Date('2020-12-31'),
            	yearRange: [2000,2020]
        	});
    	});
    });